from datetime import date, timedelta

from django.db.models import Q
from django.http import JsonResponse
from django.views import View
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import GoodsVisitCount, GoodsCategory
from meiduo_admin.serializers.sku import GoodsVisitCountSerialize
from orders.models import OrderInfo
from users.models import User


class StatisticalView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # authentication_classes = [SessionAuthentication]
        datetime = date.today()
        count = User.objects.all().count()

        return Response({
            'count': count,
            'data': datetime
        })


class DayilyActiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        datetime = date.today()

        count = User.objects.filter(last_login__gte=datetime).count()

        return Response({'count': count,
                         'date': datetime})


class DayOrdersView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        datetime = date.today()

        count = OrderInfo.objects.filter(Q(status__in=[2, 3, 4, 5]) & Q(update_time__gte=datetime)).values(
            'user_id').distinct().count()

        return Response({'count': count,
                         'date': datetime})


class MonthIncrementView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # # datetime = date.today()
        #
        # user = User.objects.all()
        # all_list = []
        #
        # for joined in user:
        #     datetime = joined.date_joined
        #     datechange = datetime.date()
        #     print(datechange)
        #     count = User.objects.filter(date_joined__contains=datechange).count()
        #     all_list.append({
        #         'count': count,
        #         'date': datechange
        #     })
        #
        # return Response(all_list)

        now_date = date.today()
        start_date = now_date - timedelta(days=30)
        date_list = []
        for i in range(30):
            index_date = start_date + timedelta(days=i + 1)

            cur_date = start_date + timedelta(days=i + 2)
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()

            date_list.append({
                'count': count,
                'date': index_date
            })
        return Response(date_list)


class DayIncrementView(APIView):
    def get(self, request):
        new_date = date.today()

        count = User.objects.filter(date_joined__gte=new_date).count()
        return Response({
            'count': count,
            'date': new_date
        })


class VisitView(View):
    def post(self, request, category_id):
        new_date = date.today()
        try:
            visit = GoodsVisitCount.objects.filter(date=new_date)
        except Exception as e:
            # visit.count += 1
            # visit.save()

            visit = GoodsVisitCount(
                category_id=category_id,
                count=1,
                date=new_date
            )
            visit.save()
            return JsonResponse({
                'code': 200,
                'errmsg': 'ok'
            })
        lists = []
        for i in visit:
            lists.append(i.category_id)
        print(category_id)
        if category_id in lists:
            visit = GoodsVisitCount(
                category_id=category_id,
                count=1,
                date=new_date
            )
            visit.save()
        else:
            visit = GoodsVisitCount.objects.get(date=new_date,
                                                category_id=category_id)
            visit.count += 1
            visit.save()
        return JsonResponse({
            'code': 200,
            'errmsg': 'ok'
        })


# class GoodsDayView(ModelViewSet):
#     serializer_class = GoodsVisitCountSerialize
#     queryset = GoodsVisitCount.objects.all()
#
#     def list(self, request, *args, **kwargs):
#         serializer = self.get_serializer(self.queryset, many=True)
#         print(serializer.data)
#         return Response(serializer.data)


class GoodsDayView(APIView):
    def get(self, request):
        new_date = date.today()
        queryset = GoodsVisitCount.objects.filter(date=new_date)
        serializer = GoodsVisitCountSerialize(queryset, many=True)


        return Response(serializer.data)
